package com.rachel.testjetpack;

import android.util.Log;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.rachel.testjetpack.livedata.Main4ActivityViewModel;
import com.rachel.testjetpack.viewmodel.Main3ActivityViewModel;

/**
 * Android Jetpack系列之LiveData
 */
public class WorkUtil4 implements LifecycleObserver {

    private static final String TAG = "WorkUtil";

    private boolean whetherToCount = true;

    private Main4ActivityViewModel viewModel;

    public WorkUtil4(Main4ActivityViewModel viewModel) {
        this.viewModel = viewModel;
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (whetherToCount) {
                    try {
                        Thread.sleep(1000);
                        viewModel.add();
                        Log.d(TAG, "start: " + viewModel.getCount());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        viewModel.setCount(100);
        whetherToCount = false;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestory() {
        viewModel.setCount(0);
    }
}